import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class HomeBanner extends StatelessWidget {
  const HomeBanner({super.key, required this.bannerList});

  // 定义列表接收父组件传值
  final List bannerList;

  @override
  Widget build(BuildContext context) {
    // 创建轮播图项列表
    List<Widget> carouselItems = [];
    
    if (bannerList.isNotEmpty) {
      // 有真实数据时，显示实际的轮播图
      carouselItems = bannerList
          .map((item) => GestureDetector(
                // 点击操作 
                onTap: () {
                  if (kDebugMode) {
                    print('点击了, id:${item['imgName']}');
                  }
                },
                child: Container(
                  margin: const EdgeInsets.all(5),
                  child: Image.network(
                    item['imgUrl'],
                    fit: BoxFit.cover,
                    // 添加加载状态处理
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return Container(
                        color: Colors.grey[100],
                        alignment: Alignment.center,
                        child: const CircularProgressIndicator(),
                      );
                    },
                  ),
                ),
              ))
          .toList();
    } else {
      // 无数据时，显示占位图
      carouselItems = [
        Container(
          margin: const EdgeInsets.all(5),
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(4),
          ),
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.image_outlined,
                size: 40,
                color: Colors.grey[400],
              ),
              const SizedBox(height: 8),
              Text(
                '加载中...',
                style: TextStyle(
                  color: Colors.grey[500],
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ),
      ];
    }

    return CarouselSlider(
      items: carouselItems,
      // 常用配置
      options: CarouselOptions(
        autoPlay: bannerList.isNotEmpty, // 只有有数据时才自动播放
        autoPlayInterval: const Duration(seconds: 2),
        height: 150,
        viewportFraction: 1.0,
        enableInfiniteScroll: bannerList.isNotEmpty, // 只有有数据时才无限滚动
      ),
    );
  }
}